import { reactive, ref, watch, computed } from "vue";
import { getNativeCode, getVipLeaveList, findOrderStatus, getVipInfo } from "../../service/pay"
import { useUserStore } from "../../store/user"
import { onBeforeRouteLeave } from "vue-router"



export const useVipCenterHooks = () => {
  const vipList = reactive([{
    name:'SVIP',
    url:new URL('@/assets/image/图层 12.png',import.meta.url).href,
    color:'#A97737',
    list:[]
  },{
    name:'VIP',
    url:new URL('@/assets/image/carousel-vip2.png',import.meta.url).href,
    color:'#0680A5',
    list:[]
  },{
    name:'企业VIP',
    url:new URL('@/assets/image/carousel-vip1.png',import.meta.url).href,
    color:'#0A70AF',
    list:[]
  }])
  const userStore = useUserStore()
  const userInfo = computed((): any => userStore.userInfo)
  const priceList = ref([])
  type VipType = "super" | "base";
  // 当前vip类型
  const currVipType = ref<VipType>("super");
  // 当前支付金额
  const payPrice = ref("")

  // 会员档次
  const vipLevels = reactive<any>({
    super: [],
    base: []
  });

  // 获取vip档位信息
  getVipLeaveList().then(async res => {
    const {data} = res;
    vipList.forEach(item=>{
      data.forEach(val=>{
        if(val.type==1&&item.name=='VIP'){
          item.list.push( val)
        }else if(val.type==2&&item.name=='SVIP'){
          item.list.push( val)
        }else if(val.type==3&&item.name=='企业VIP'){
          item.list.push(val)
        }
      })
    })
    // 获取当前vip升级svip信息
    // console.log(res,'---')

    // if (userInfo.value.vip == 1) {
    //   const result = await getVipInfo()
    //   const { residueDay, upgradePrice } = result.data
    //   console.log(result.data);

    //   data.unshift({ id: -999, name: "升级成SVIP", price: upgradePrice, time: residueDay, type: 2, timeUnit: "DAY" })
    //   payPrice.value = upgradePrice
    // }

    // vipLevels.super = data.filter((res: any) => res.type == 2)
    // vipLevels.base = data.filter((res: any) => res.type == 1)
  })
  const vipType = ref()
  const vipId = ref()
  const memberExpirationDate = ref('')
  const vipPrice = ref()
  const rechargeVip = (type,id,item)=>{
    console.log(item)
    vipType.value = type||2
    vipId.value = id ||5
    vipPrice.value = item?.price ||1000
    const now = new Date();
      // 假设会员期限是一个月，可以根据需要调整
      // const expirationMonths = 1;
      now.setMonth(now.getMonth() + item?.time||3);
      memberExpirationDate.value = now.toISOString().split('T')[0];

    getNativeCode({ vipInfoId: id||5 }).then(res => {
      wxQrCode.value = res.data.codeUrl
    })
  }
  // 当前所选择的vip档次
  const currVipLevelTypes = ref({
    super: -999,
    base: 1
  });




  // 更换当前vip档次
  const changeCurrVipLevelType = (id: number) => {
    currVipLevelTypes.value[currVipType.value] = id;
  };

  // 改变当前vip充值类型
  const changeVipType = (vipType: VipType) => {
    currVipType.value = vipType;
  };

  const wxQrCode = ref("");
  const zfbQrCode = ref("");


  const pollOrderStatus = () => {

  }

  let timer: any = null

  // 监听currVipType和currVipLevelTypes变化,进而获取新的支付码
  // watch(
  //   () => [currVipLevelTypes.value, currVipType.value],
  //   (newVal, oldVal) => {
  //     // 避免存在多个定时器任务
  //     if (timer) {
  //       clearInterval(timer);
  //       timer = null;
  //     }
  //     // 设置金额

  //     // 请求微信支付二维码
  //     wxQrCode.value = ""
  //     console.log(currVipLevelTypes.value,'currVipLevelTypes')
  //     console.log(currVipType.value,'currVipType')

  //     const payID = currVipLevelTypes.value[currVipType.value] === -999 ? 2 : currVipLevelTypes.value[currVipType.value]
  //     getNativeCode({ vipInfoId: payID }).then(res => {
  //       if (!res) {
  //         return wxQrCode.value = "系统错误,请联系管理员处理!"
  //       }
  //       wxQrCode.value = res.data.codeUrl || "系统错误,请联系管理员处理!"

  //       const priceItem: any = vipLevels[currVipType.value].filter((item: any) => item.id === currVipLevelTypes.value[currVipType.value])[0]
  //       console.log("执行了", vipLevels["super"]);

  //       payPrice.value = priceItem["price"]
  //       // 请求完成后进行轮询订单状态
  //       timer = setInterval(() => {
  //         // 发起网络请求
  //         findOrderStatus(res.data.orderId).then((res: any) => {
  //           if (res.data) {
  //             clearInterval(timer)
  //             timer = null
  //             ElMessageBox.alert(
  //               '恭喜您，成功加入透策会员。',
  //               '提示',
  //               {
  //                 confirmButtonText: '确定',
  //                 type: 'success',
  //                 center: true,
  //                 callback: () => {
  //                   // 重新请求用户数据
  //                   userStore.getUserInfo()
  //                   userStore.updateUserAuth()
  //                 }
  //               }
  //             )
  //           }
  //         })
  //       }, 5000)
  //     })
  //   },
  //   {
  //     deep: true,
  //     immediate: true
  //   }
  // );


  // 路由离开时清空定时器
  onBeforeRouteLeave((to, from) => {
    clearInterval(timer)
    timer = null
  })
  return {
    currVipType,
    changeVipType,
    vipLevels,
    currVipLevelTypes,
    changeCurrVipLevelType,
    wxQrCode,
    zfbQrCode,
    userInfo,
    payPrice,
    priceList,
    vipList,
    rechargeVip,
    memberExpirationDate,
    vipType,
    vipId,
    vipPrice
  };
};
